package com.wkzn.serialdemo;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity implements SerialInputOutputManager.Listener {
    private Context context;
    private TextView tvShow;
    private TextView tvErr;

    private UsbSerialPort port;
    private UsbDeviceConnection connection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            Runtime.getRuntime().exec("su");
        } catch (IOException e) {
            Toast.makeText(context, "获取root权限失败", Toast.LENGTH_SHORT).show();
        }
        context = this;
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
                final List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
                if (availableDrivers.isEmpty()) {
                    Toast.makeText(context, "没有搜索到设备", Toast.LENGTH_SHORT).show();
                    // Open a connection to the first available driver.


                } else if (availableDrivers.size() == 1) {
                    Toast.makeText(context, "搜索到一个设备,正在连接", Toast.LENGTH_SHORT).show();
                    connect(availableDrivers.get(0), manager);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    ArrayList<String> strings = new ArrayList<>();
                    for (int i = 0; i < availableDrivers.size(); i++) {
                        String deviceName = availableDrivers.get(i).getDevice().getDeviceName();
                        strings.add(deviceName);
                    }
                    int size = strings.size();
                    builder.setItems(strings.toArray(new String[size]), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            connect(availableDrivers.get(which), manager);
                        }
                    }).show();
                    Toast.makeText(context, "搜索到多个设备", Toast.LENGTH_SHORT).show();
                }


            }
        });
        findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int write = port.write("AA 07 09 03 08 01 04 CA".getBytes(), 3000);
                    Toast.makeText(context, "发送数据状态码" + write, Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        });
        tvShow = findViewById(R.id.tv_show);
        tvErr = findViewById(R.id.tv_err);
        findViewById(R.id.tv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    port.close();

                } catch (IOException e) {
                    Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
        });
        findViewById(R.id.tv_open).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    port.open(connection);
                    port.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
                } catch (IOException e) {
                    Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
        });
    }


    private void connect(UsbSerialDriver driver, UsbManager manager) {


        connection = manager.openDevice(driver.getDevice());
        if (connection == null) {
            Toast.makeText(context, "缺少权限,授权后请重新搜索", Toast.LENGTH_SHORT).show();
            // add UsbManager.requestPermission(driver.getDevice(), ..) handling here

            manager.requestPermission(driver.getDevice(), PendingIntent.getService(context, 0, new Intent(),

                    PendingIntent.FLAG_UPDATE_CURRENT));
            return;
        }

        port = driver.getPorts().get(0); // Most devices have just one port (port 0)

        try {
            port.open(connection);
            port.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

            boolean open = port.isOpen();
            Toast.makeText(context, "串口开启返回" + open, Toast.LENGTH_SHORT).show();

            SerialInputOutputManager serialInputOutputManager = new SerialInputOutputManager(port, this);
            Executors.newSingleThreadExecutor().submit(serialInputOutputManager);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onNewData(final byte[] data) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvShow.setText("收到数据" + new String(data));
            }
        });
    }

    @Override
    public void onRunError(final Exception e) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvErr.setText("收到数据" + e.getMessage());
            }
        });
    }
}